package com.sdkx.app.ViewModel;

import android.text.TextUtils;

import com.sdkx.app.model.WayPoint;
import com.sdkx.app.model.AirWaySegment;
import com.sdkx.app.model.DistanceObject;
import com.sdkx.app.util.CharacterParser;
import com.sdkx.app.util.PinyinComparator;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 航点业务管理类
 */
public class WayPointManager {

    /**
     * 批量查询航点，如果name为null则返回所有数据，否则返回所有名称类似name的数据
     *
     * @param name
     * @return
     */
    public static List<WayPoint> getItems(String name) {
        if ((name == null) || (name.equals(""))) {
            return LitePal.findAll(WayPoint.class);
        } else {
            return LitePal.where("name like ?", "%" + name + "%").find(WayPoint.class);
        }
    }

    public static WayPoint getItem(int id) {
        List<WayPoint> wayPoints = LitePal.where("id = ?", String.valueOf(id)).find(WayPoint.class);
        if (wayPoints.size() > 0)
            return wayPoints.get(0);
        else
            return null;
    }

    /**
     * 查询是否用同名航点
     *
     * @param name
     * @return
     */
    public static boolean getSame(String name) {
        if ((name == null) || (name.equals(""))) {
            return false;
        } else {
            return (LitePal.where("name =?", name).find(WayPoint.class)).size() > 0;
        }
    }

    /**
     * 查询当前点是否已经被航线使用
     *
     * @param id
     * @return true 代表被使用，false 代表未被使用
     */
    public static boolean getIfUsedByLine(int id) {
        return LitePal.where("wayPointId = ?", String.valueOf(id)).find(AirWaySegment.class).size() > 0;
    }

    /**
     * 获取指定类型的航点集合
     *
     * @param type
     * @return
     */
    public static List<WayPoint> getItemsByType(int type) {
        return LitePal.where("type = ?", String.valueOf(type)).find(WayPoint.class);
    }

    /**
     * 按照需求分页取出数据
     *
     * @param types    数据类型
     * @param offset   偏移量
     * @param pagesize 每页数据量
     * @return
     */
    public static List<WayPoint> getItemsByTypelimit(int[] types, int offset, int pagesize) {
        StringBuilder builder = new StringBuilder();
        int count = 0;
        builder.append("type in ( ");
        for (int type : types) {
            count++;
            builder.append(type);
            if (count != types.length) {
                builder.append(",");
            }
        }
        builder.append(" ) limit ? offset ?");
        return LitePal.where(builder.toString(), String.valueOf(pagesize), String.valueOf(offset)).find(WayPoint.class);
    }

    public static List<WayPoint> serchWayPoint(int[] types, String keywords) {
        StringBuilder builder = new StringBuilder();
        builder.append("type in ( ");
        int count = 0;
        for (int type : types) {
            count++;
            builder.append(type);
            if (count != types.length) {
                builder.append(",");
            }
        }
        builder.append(" ) and (name like '%");
        builder.append(keywords);
        builder.append("%' ");
        builder.append("or pyname like '%");
        builder.append(keywords);
        builder.append("%' ");
        builder.append("or xsname like '%");
        builder.append(keywords);
        builder.append("%')");
        String info = builder.toString();
        return LitePal.where(info).find(WayPoint.class);
    }

    /**
     * 获取多个类型的点集合
     *
     * @param types
     * @return
     */
    public static List<WayPoint> getItemsByTypes(int[] types) {
        String[] queryStr = new String[types.length + 1];
        String tempStr = "";
        for (int i = 0; i < types.length; i++) {
            if (i != 0)
                tempStr += " or ";
            tempStr += "type = ?";
        }
        queryStr[0] = tempStr;
        int j = 1;
        for (int type : types) {
            queryStr[j++] = String.valueOf(type);
        }
        return LitePal.where(queryStr).find(WayPoint.class);
    }

    public static List<WayPoint> getItemsByTypesAndName(int[] types, String keyword) {
        String[] queryStr = new String[types.length + 2];
        String tempStr = "";
        for (int i = 0; i < types.length; i++) {
            if (i != 0)
                tempStr += " or ";
            else
                tempStr += "( ";
            tempStr += "type = ?";
        }
        tempStr += " ) and name like ?";
        queryStr[0] = tempStr;
        int j = 1;
        for (int type : types) {
            queryStr[j++] = String.valueOf(type);
        }
        queryStr[queryStr.length - 1] = "%" + keyword + "%";
        return LitePal.where(queryStr).find(WayPoint.class);
    }

    /**
     * 查询机场中名称类似keyword的数据
     *
     * @param keyword
     * @return
     */
    public static List<WayPoint> getAirportsLike(String keyword) {
        String queryStr = "(type = ? or type = ? or type = ?) and name like ?";
        return LitePal.where(
                queryStr,
                String.valueOf(WayPoint.WayPointType.MILITARY_AIRPORT.ordinal()),
                String.valueOf(WayPoint.WayPointType.AIS_AIRPORT.ordinal()),
                String.valueOf(WayPoint.WayPointType.AM_AIRPORT.ordinal()),
                "%" + keyword + "%"
        ).find(WayPoint.class);
    }

    /**
     * 在航点中查询名称类似keyword的数据
     *
     * @param keyword
     * @return
     */
    public static List<WayPoint> getPointLike(String keyword) {
        String queryStr = "(type = ? or type = ? or type = ? or type = ? or type = ?) and name like ?";
        return LitePal.where(
                queryStr,
                String.valueOf(WayPoint.WayPointType.AIS_NDB.ordinal()),
                String.valueOf(WayPoint.WayPointType.AIS_VOR_DME.ordinal()),
                String.valueOf(WayPoint.WayPointType.AIS_POINT.ordinal()),
                String.valueOf(WayPoint.WayPointType.MILITARY_POINT.ordinal()),
                String.valueOf(WayPoint.WayPointType.PERSON_POINT.ordinal()),
                "%" + keyword + "%"
        ).find(WayPoint.class);
    }

    /**
     * 获取距离指定地点距离最近的几个点
     *
     * @param lon
     * @param lat
     * @param limit 获取点数目
     * @param types 类型，null代表所有类型
     * @return
     */
    public static List<WayPoint> getItemsByDistance(double lon, double lat, int limit, int[] types) {
        List<WayPoint> points;
        if (types == null)
            points = getItems(null);
        else
            points = getItemsByTypes(types);
        List<DistanceObject> tempObjects = new ArrayList<>();
        for (WayPoint wayPoint : points
                ) {
            //TODO：数据库接口更改，需要重新编写代码逻辑
//            DistanceObject tempObject = new DistanceObject(wayPoint.getId(), SearchHelper.distanceOfLatLong(lon, lat, wayPoint.getLongitude(), wayPoint.getLatitude()));
//            tempObjects.add(tempObject);
        }
        Collections.sort(tempObjects);
        if (limit > tempObjects.size())
            limit = tempObjects.size();
        tempObjects = tempObjects.subList(0, limit);
        List<WayPoint> newList = new ArrayList<>();
        for (DistanceObject distanceObject : tempObjects
                ) {
            for (WayPoint wayPoint : points
                    ) {
                if (wayPoint.getId() == distanceObject.getId()) {
                    newList.add(wayPoint);
                    break;
                }
            }
        }
        return newList;
    }

    /**
     * 判断名称是否已经使用
     *
     * @param name
     * @return
     */
    public static boolean cotains(String name) {
        return LitePal.where("name = ?", name).count(WayPoint.class) > 0;
    }

    /**
     * 查询指定航点
     *
     * @param name
     * @return
     */
    public static WayPoint getItem(String name) {
        List<WayPoint> wayPoints = LitePal.where("name = ?", name).find(WayPoint.class);
        if (wayPoints.size() > 0)
            return wayPoints.get(0);
        else
            return null;
    }

    /**
     * 新建航点，如果航点名称已经存在则返回false
     *
     * @param wayPoint
     * @return
     */
    public static boolean insert(WayPoint wayPoint) {
        if (wayPoint == null) {
            return false;
        }
        return wayPoint.save();
    }

    /**
     * 批量存储，大量数据存储时采用此方法速度较快
     *
     * @param wayPoints
     */
    public static void insertList(List<WayPoint> wayPoints) {
        if (wayPoints == null) {
            return;
        }
        LitePal.saveAll(wayPoints);
    }

    /**
     * 删除航点
     *
     * @param name
     */
    public static void delete(String name) {
        LitePal.deleteAll(WayPoint.class, "name = ?", name);
    }

    /**
     * 删除所有航点数据
     */
    public static void deleteAll() {
        LitePal.deleteAll(WayPoint.class);
    }

    /**
     * 更新航点信息，此航点对象必须是已经持久化的对象
     *
     * @param wayPoint
     */
    public static void update(WayPoint wayPoint) {
        if (wayPoint == null || !wayPoint.isSaved())
            return;
        wayPoint.update(wayPoint.getId());
    }

    /**
     * 汉字转换成拼音的类
     */
    private static CharacterParser characterParser = CharacterParser.getInstance();

    //填充单个数据
    public static void filleditem(WayPoint sortModel) {
        //TODO：数据库接口更改，需要重新编写代码逻辑
//        sortModel.setSortLetters("#");
//        if (sortModel.getName() == (null)) return;
//        if (sortModel.getName().equals("")) return;
//        // 汉字转换成拼音
//        String pinyin = CharacterParser.getInstance().getSelling(sortModel.getName());
//        if (pinyin.length() < 1) {
//            sortModel.setSortLetters("#");
//        }
//        String sortString = pinyin.substring(0, 1).toUpperCase();
//
//        // 正则表达式，判断首字母是否是英文字母
//        if (sortString.matches("[A-Z]")) {
//            sortModel.setSortLetters(sortString.toUpperCase());
//        } else {
//            sortModel.setSortLetters("#");
//        }
    }

    public static void filledData(List<WayPoint> date) {
        if (characterParser == null) characterParser = CharacterParser.getInstance();
        for (int i = 0; i < date.size(); i++) {
            WayPoint sortModel = date.get(i);
            filleditem(sortModel);
        }
    }

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    public static PinyinComparator pinyinComparator;

    /**
     * 根据航点输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    public static List<WayPoint> filterData(String filterStr, List<WayPoint> mWPList) {
        List<WayPoint> filterDateList = new ArrayList<WayPoint>();

        if (pinyinComparator == null) pinyinComparator = new PinyinComparator();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = mWPList;
        } else {
            filterDateList.clear();
            String name, pyname, sxname;//名称，拼音，拼音缩写
            filterStr = filterStr.toUpperCase();
            for (WayPoint sortModel : mWPList) {
                if (sortModel.getName() == null) continue;
                name = sortModel.getName().toUpperCase();
                pyname = CharacterParser.getInstance().getSelling(name).toUpperCase();
                sxname = CharacterParser.getInstance().getSellingSX(name).toUpperCase();
                if (-1 != (name.indexOf(filterStr))
                        || pyname.startsWith(filterStr)
                        || -1 != (sxname.indexOf(filterStr))
                        ) {
                    filterDateList.add(sortModel);
                }

            }
        }
        if (pinyinComparator == null) pinyinComparator = new PinyinComparator();
        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        return filterDateList;
//        AppData.wpsadapter.updateListView(filterDateList);
    }

}
